// <script type="application/javascript" src="/c19032/semiautomatic/stomp.js" ></script>
// <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

var cellCanvas = document.getElementById("cellcanvas");
var craneCanvas = document.getElementById("cranecanvas");
var locationCanvas = document.getElementById("locationcanvas");
var cellCanvasCtx = cellCanvas.getContext('2d');
var locationCanvasCtx = locationCanvas.getContext('2d');
var craneCanvasCtx = craneCanvas.getContext('2d');
var beginLocation = [];
var endLocations = [];

var disabledNewLocations = [];
var disabledLocations = [];
var isSelectRegion = false;
var isSelectRegionIng = false;
var isSelectBegin = true;

//屏蔽区域选择
var isSelectDisabled = false;
var deleteCellDisabledLocation = [];
var deleteOutPortDisabledLocation = [];
var poolInfo = [];


var beginZoneList = [];
var endZoneList = [];
var selectBeginInputTmp = [];
var selectEndInputTmp = [];
var currentSelectedCrane = 3;


//混料模式数据存储
var area1Location = [];
var area2Location = [];
var area3Location = [];
var areaEndLocation = [];
var selectMode = 1;
var isMixTaskMode = false;

var faultStatus = false;

//天车图片
var craneimage1 = new Image();
var craneimage2 = new Image();
var craneimage3 = new Image();
var craneimage4 = new Image();

layui.config({
    base: CXL.ctxPath + '/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'table', 'laydate', 'form', 'layer', 'element'], function () {
        var admin = layui.admin;
        var table = layui.table;
        var laydate = layui.laydate;
        var $ = layui.$;
        var form = layui.form;
        let element = layui.element;
        let router = layui.router();


        let resetButton = document.getElementById("resetButton");

        // <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
        //开始点和结束点


        var colorList = {
            c0: "rgb(0,0,255)"
            , c1: "rgb(0,150,250)"
            , c2: "rgb(0,200,200)"
            , c3: "rgb(0,250,100)"
            , c4: "rgb(50,255,50)"
            , c5: "rgb(0,191,255)"
            , c6: "rgb(150,255,0)"
            , c7: "rgb(255,230,0)"
            , c8: "rgb(189,26,230)"
            , c9: "rgb(128,128,128)"
            , cmax: "#B03060"
        };

        var colorArr = ["#ffffcc", "#ffcccc", "#d9d2e9", "#9966cc", "#000000"];
        var heightColorArr = ["#33FF00", "#66FF00", "#99FF00", "#CCFF00", "#FFFF00", "#FFCC00", "#FF9900", "#FF6600", "#FF3300", "#FF0000"];


        var corrections = [
            {
                name: "B01",
                text: "干燥仓"
            }
            , {
                name: "B11",
                text: "烟煤仓"
            }
            , {
                name: "B21",
                text: "1号仓"
            }
            , {
                name: "B22",
                text: "2号仓"

            }
            , {
                name: "B23",
                text: "3号仓"

            }
            , {
                name: "B24",
                text: "4号仓"

            }
            , {
                name: "B25",
                text: "5号仓"

            }
            , {
                name: "B26",
                text: "6号仓"

            }
            , {
                name: "B27",
                text: "7号仓"

            }
            , {
                name: "B28",
                text: "8号仓"

            }
            , {
                name: "B29",
                text: "9号仓"

            }
            , {
                name: "B30",
                text: "10号仓"
            }
            , {
                name: "B31",
                text: "11号仓"

            }
            , {
                name: "B32",
                text: "12号仓"
            }
            , {
                name: "B40",
                text: "人工上料仓"
            }

        ];

        var zoneInfoCollection = [];

        var outportMap = [];
        var cellMap = [];
        var cellLocations = [];
        var carsList = [];
        var tagList = [];
        var webSocketTagListStep = 4;


        //拖选相关
        var drawingSurfaceImageData;
        var mousedown = {};
        var rubberbandRect = {};
        var dragging = false;

        //背景图片
        var craneRuler = new Image();
        // debugger;
        craneRuler.src = CXL.ctxPath + '/assets/semiautomatic/craneRuler.png';


        //偏移量
        var xOffset = -100;
        var yOffset = 0;

        //物料存储变量submitWay
        var materialList = [];
        var loadMaterialFlag = false;


        // openWebSocket();
        // setTimeout(initMap(), 1000);
        initMap();
        connect();


        // displayTraState("getTra1State");
        // displayTraState("getTra2State");
        // displayTraState("getTra3State");
        // displayTraState("getTra4State");
        // setTimeout()
        // setInterval(sendMessageNoParameter(),2000);
        // subscribeSocket();
        // setTimeout(sendMessageNoParameter(),3000);
        // setTimeout(sendMessageNoParameter,2000);
        // setTimeout(sendMessageNoParameter(),2000);
        // setTimeout(sendMessageNoParameter(),2000);

        cellCanvas.addEventListener("click", areaClickCanvas);
        cellCanvas.addEventListener("mousedown", areaMouseDownCanvas);
        cellCanvas.addEventListener("mousemove", areaMouseMoveCanvas);
        cellCanvas.addEventListener("mouseup", areaMouseUpCanvas);


        //定时刷新
        self.setInterval(function () {
            getCellLocations();
            for (j = 0 , len = cellLocations.length; j < len; j++) {
                if (cellLocations[j].height != cellMap[j].height) {
                    cellMap[j].height = cellLocations[j].height;
                }
                if (cellMap[j].color != colorList.c5 && cellMap[j].color != colorList.cmax && cellMap[j].color != colorList.c8  && cellMap[j].color != colorList.c9 && cellMap[j].color != colorArr[4]) {
                    cellMap[j].color = getCellColor(cellMap[j]);
                }

            }
            drawCellMap(xOffset, yOffset);
        }, 60000);
        self.setInterval(function () {
            drawCraneLocation(thirdCraneLocation, thirdCraneLocationY);
            updateCraneLocations();
        }, 500);


        //报警弹窗
        window.logFault = function (faultsta) {
            // console.log(faultsta);
            if (faultsta === true && faultStatus === false) {
                CXL.error(currentSelectedCrane + "号天车报警，请检查报警输入");
            }
            faultStatus = faultsta;
        }
        element.on('tab(switchTaskType)', function () {
            location.hash = 'switchTaskType=' + this.getAttribute('lay-id');
            if (this.getAttribute('lay-id') === "mixTask") {
                if (loadMaterialFlag === false) {
                    getMaterial();
                }
                initMap();
                resetSelectedFree();
                isSelectBegin = false;
                isMixTaskMode = true;
            } else {
                isMixTaskMode = false;
                initMap();
                resetSelectedFree();
                if (isSelectRegion) {
                    $("#regionMode").prop('checked', 'true');
                } else {
                    $("#pointMode").prop('checked', 'true');
                }
                isSelectBegin = true;
                $("#beginselect").prop('checked', 'true');
                form.render();
            }
            // console.log(location.hash);
        });


        form.on('radio(isSelectBegin)', function (data) {
            if (data.value == "true") {
                isSelectBegin = true;
            } else {
                isSelectBegin = false;
            }
            if (isSelectBegin) {
                layer.msg("当前请选择起始点");
            } else {
                layer.msg("当前请选择终点");
            }
        });


        form.on('radio(selectAreaModeRadio)', function (data) {
            switch (data.value){
                case "1":
                    selectMode = 1;
                    break;
                case "2":
                    selectMode = 2;
                    break;
                case "3":
                    selectMode = 3;
                    break;
                case "4":
                    selectMode = 4;
                    break;
                default:
                    selectMode = 1;
            }
        });
        form.on('checkbox(selectDisabled)', function (data) {
            if (data.elem.checked === true) {
                isSelectDisabled = true;
                deleteCellDisabledLocation = [];
                deleteOutPortDisabledLocation = [];
                resetSelected();
                // initMap();
                layer.msg("当前为选择屏蔽区域模式！");
            } else {
                isSelectDisabled = false;
                resetSelected();
                // initMap();
            }
        });

        //天车选择器
        form.on('radio(CraneRadio)', function (data) {
            currentSelectedCrane = data.value;
            var craneid = parseInt(currentSelectedCrane);
            var queryData = {};
            queryData['craneId'] = craneid;
            table.reload(Page.tableId, {where: queryData});
        });

        //工作模式选择器监听

        form.on('radio(WorkModeRadio)', function (data) {
            switch (data.value) {
                case "move":
                    $('#workFrequency').val(1);
                    $('#catchNumberInput').val(1);
                    $("#beginselect").removeAttr("disabled");
                    $("#endselect").attr("disabled", true);
                    $("#beginselect").prop('checked', 'true');
                    isSelectBegin = true;
                    resetEndSelected();
                    form.render();
                    break;
                case "dump":
                    $('#workFrequency').val(1);
                    $('#catchNumberInput').val(1);
                    $("#beginselect").attr("disabled", true);
                    $("#endselect").removeAttr("disabled");
                    $("#endselect").prop('checked', 'true');
                    isSelectBegin = false;
                    resetBeginSelected();
                    form.render();
                    break;
                case "load":
                    $("#beginselect").removeAttr("disabled");
                    $("#endselect").removeAttr("disabled");
                    $("#beginselect").prop('checked', 'true');
                    resetEndSelected();
                    isSelectBegin = true;
                    form.render();
                    break;
                case "pour":
                    $("#beginselect").removeAttr("disabled");
                    $("#endselect").removeAttr("disabled");
                    $("#beginselect").prop('checked', 'true');
                    isSelectBegin = true;
                    resetEndSelected();
                    form.render();
                    break;
                default:
                    break;
            }
        });
        //监听无限次
        form.on('checkbox(switchFrquencyForever)', function (data) {
            if (data.elem.checked) {　　　　　　//判断当前多选框是选中还是取消选中
                $('#workFrequency').val(0);
                $('#workFrequency').attr('disabled', true);
            } else {
                $('#workFrequency').val('');
                $('#workFrequency').removeAttr('disabled', true);
            }
        });

        form.on('radio(ChoiceRadio)', function (data) {

            if (data.value == "1") {
                isSelectRegion = true;
            } else {
                isSelectRegion = false;
            }

        });

        form.on('radio(ChoiceRadioForMix)', function (data) {

            if (data.value == "1") {
                isSelectRegion = true;
            } else {
                isSelectRegion = false;
            }

        });
//保存动作
        form.on('submit(submitWay)', function (data) {
            var inputDataJson = JSON.stringify(data.field);
            var beginLocationJson = JSON.stringify(beginLocation);
            var endLocationJson = JSON.stringify(endLocations);
            $.ajax({
                url: CXL.ctxPath + "/semiautomaticway/saveway",
                data: {
                    craneId: currentSelectedCrane,
                    inputData: inputDataJson,
                    beginLocationList: beginLocationJson,
                    endLocationList: endLocationJson,
                },
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.success) {
                        CXL.success("保存成功。");
                        table.reload(Page.tableId, {
                            where: {
                                key: {
                                    craneId: currentSelectedCrane
                                }
                            }
                        });
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        });
//提交任务
        form.on('submit(taskForm)', function (data) {
            // console.log(data.field.selectWorkModel);
            if (beginLocation.length === 0 && endLocations.length === 0) {
                CXL.error("请勿提交空任务！")
            } else if (data.field.selectWorkModel === "move" && endLocations.length != 0 && beginLocation.length != 1) {
                CXL.error("请正确选择移动位置！")
            } else if (parseInt(data.field.catchNumber) < 1 || parseInt(data.field.catchNumber) > 6) {
                CXL.error("抓取次数错误！")
            } else if (data.field.selectWorkModel === "load" && endLocations.length != 1) {
                CXL.error("上料模式只可选择一个终点！")
            } else if (data.field.selectWorkModel === "dump" && endLocations.length != 1 && beginLocation.length != 0) {
                CXL.error("放料模式只可选择一个终点！")
            } else {
                if (data.field.selectWorkModel === "load") {
                    if (checkGrabAndOutput(beginLocation, endLocations[0])) {
                        postTask(data);
                    } else {
                        layer.confirm('当前抓点内可能有不符物料！确认提交吗？', {
                            btn: ['确定', '取消'] //按钮
                        }, function (index) {
                            postTask(data);
                            layer.close(index);
                        }, function () {
                            layer.close(index);
                        });
                    }
                } else {
                    postTask(data);
                }


            }
        });

        //判断是否上料错误
        function checkGrabAndOutput(beginLocations, output) {
            // let output = endLocations[0];
            let materialName = output.materialName;
            for (let item of beginLocations) {
                if (item.materialName != materialName) {
                    return false;
                }
            }
            return true;
        }

        form.on('submit(mixTaskPost)', function (data) {
            if (area1Location.length === 0) {
                CXL.error("请勿提交空任务！")
            } else if (area1Location.length > 0 && area2Location ==  0 && area3Location > 0) {
                CXL.error("请正确选择参数")
            }  else {
                postMixTask(data);
            }

            // console.log(data);

        });


        // resetSelected
        //提交屏蔽区域
        form.on('submit(submitDisabled)', function (data) {
            var disabledJson = JSON.stringify(disabledLocations);
            var disableNewJson = JSON.stringify(disabledNewLocations);
            // console.log(disabledNewLocations);
            layer.confirm('确认提交吗', function (index) {

                $.ajax({
                    url: CXL.ctxPath + "/semiautomatic/submitDisabledArea",
                    data: {
                        disabledLocations: disabledJson,
                        disabledNewLocations: disableNewJson
                    },
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.success) {
                            CXL.success("保存成功。");
                            disabledNewLocations = [];
                            initMap();
                        } else {
                            CXL.error(res.msg);
                        }
                    },
                    fail: function () {
                        CXL.error("网络错误！");
                    }
                });

                layer.close(index);
            });

        });


        /**
         * 表格参数
         */
        var Page = {
            tableId: 'actionTable',
            url: '/boot/semiautomaticway/datagrid',
            toolbar: '#table-toolbar',
            // where:{field:'createDate', order:'desc'},
            initColumn: function () {
                return [[
                    // {type: 'numbers'},
                    {field: 'id', title: 'ID', width: 80}
                    , {field: 'name', title: '动作名称', width: 180}
                    , {field: 'craneId', title: '天车ID', width: 80}
                    , {field: 'beginLocation', title: '开始位置', width: 180}
                    , {field: 'endLocation', title: '结束位置', width: 180}
                    , {
                        field: 'workMode', title: '工作模式', width: 100, templet: function (d) {
                            if (d.workMode == "WORK_TYPE_POUR") {
                                res = "倒料"
                            } else if (d.workMode == "dump") {
                                res = "放料"
                            } else if (d.workMode == "WORK_TYPE_LOAD_MATERIAL_NORMAL") {
                                res = "上料"
                            } else {
                                res = "移动"
                            }
                            return res;
                        }
                    }
                    , {field: 'catchNumber', title: '抓取次数', width: 80}
                    , {field: 'frequency', title: '运行次数', width: 80}
                    , {field: 'right', title: '操作', toolbar: '#table-toolbar', width: 115}
                ]];
            },
            deleteUrl: "/boot/semiautomaticway/delete"

        };


        /**
         * 表格的单击事件
         */
        Page.clickAction = function (obj) {

        }

        /**
         * 表格的双击事件
         */
        Page.doubleClickAction = function (obj) {

        }


        /**
         * 编辑
         */
        Page.openEdit = function (data) {
            layer.open({
                type: 2,
                title: '编辑',
                shadeClose: true,
                shade: 0.8,
                area: ['700px', '700px'],
                content: Page.addUrl + "?id=" + data.id,
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    //点击确认触发 iframe 内容中的按钮提交
                    var submit = layero.find('iframe').contents().find("#form-btn-save");
                    submit.click();

                    //刷新表格
                    Page.searchAction();
                }
            });
        };

        /**
         * 查看
         */
        Page.openDetail = function (data) {
            layer.open({
                type: 2,
                title: '查看',
                shadeClose: true,
                shade: 0.8,
                area: ['650px', '700px'],
                content: Page.addUrl + "?id=" + data.id
            });
        }

        /**
         * 删除表格数据
         */
        Page.deleteAction = function (obj) {
            parent.layer.confirm('真的确定要删除么', function (index) {

                //提交 Ajax进行后端删除
                $.ajax({
                    type: "post",
                    url: Page.deleteUrl,
                    data: {id: obj.data.id},
                    success: function (res) {
                        if (res.success) {
                            CXL.success(res.msg);
                            // layer.msg(res.msg);
                            //表格删除
                            obj.del();
                            Page.searchAction();
                            // table.reload();
                        } else {
                            CXL.warn(res.msg);
                            // layer.msg(res.msg);
                        }
                    }
                });

                layer.close(index);
            });
        }

        /**
         * 加载表格数据
         */
        Page.loadAction = function (obj) {

            beginLocation = [];
            endLocations = [];
            beginZoneList = [];
            endZoneList = [];
            getCellMap();
            getOutputMap();

            initinfo()
            // drawCellMap();
            var begin = eval(obj.data.beginLocation);
            var end = eval(obj.data.endLocation);
            let workMode = obj.data.workMode;
            let frequency = obj.data.frequency;
            let catchnumber = obj.data.catchNumber;
            let name = obj.data.name;
            let craneid = obj.data.craneId;

            for (var index in begin) {
                // addLocation(begin[index], beginLocation, colorList.c5);
                for (let item1 of cellMap) {
                    if (begin[index].name == item1.name) {
                        addLocation(item1, beginLocation, colorList.c5)
                    }
                }
                for (let item1 of outportMap) {
                    if (begin[index].name == item1.name) {
                        beginZoneList.push(item1.zoneId);
                        addLocation(item1, beginLocation, colorList.c5)
                    }
                }

            }
            for (var index in end) {
                for (let item1 of cellMap) {
                    if (end[index].name == item1.name) {
                        addLocation(item1, endLocations, colorList.cmax)
                    }
                }
                for (let item1 of outportMap) {
                    if (end[index].name == item1.name) {
                        endZoneList.push(item1.zoneId);
                        addLocation(item1, endLocations, colorList.cmax)
                    }
                }
            }

            //设定天车编号
            if (craneid == 1) {
                $("#selectFirstCrane").prop('checked', 'true');
            } else if (craneid == 2) {
                $("#selectSecondCrane").prop('checked', 'true');
            } else if (craneid == 3) {
                $("#selectThirdCrane").prop('checked', 'true');
            } else if (craneid == 4) {
                $("#selectfourthCrane").prop('checked', 'true');
            }
            //设定动作名称
            $('#actionName').val(name);

            //设定工作模式

            if (workMode == "WORK_TYPE_MOVE") {
                $("#moveMode").prop('checked', 'true');
            } else if (workMode == "WORK_TYPE_POUR") {
                $("#pourMode").prop('checked', 'true');
            } else if (workMode == "WORK_TYPE_LOAD_MATERIAL_NORMAL") {
                $("#loadMode").prop('checked', 'true');
            } else if (workMode == "WORK_TYPE_LOAD_TRUCK") {
                $("#loadTruck").prop('checked', 'true');
            }
            $('#actionName').val(name);
            //设定次数

            $('#workFrequency').val(frequency);
            if (frequency === 0) {
                // $('#isFreForever').attr('checked', 'true');
                $("#isFreForever").prop('checked', true);
                // $("input[name=is_notice][value=0]").prop("checked","true");
            } else {
                $("#isFreForever").prop('checked', false);
            }


            $('#catchNumberInput').val(catchnumber);
            form.render();
            drawCellMap(xOffset, yOffset);

        }


        /**
         * 表格渲染
         */

            // var queryData = {};
            // 查询字段
            // queryData['craneId'] = 2;
        let queryData1 = {};
        queryData1['craneId'] = 3;
        table.render({
            elem: '#' + Page.tableId
            , url: Page.url
            , where: queryData1
            // , height: 'full-140'
            , page: true
            , limit: 9
            , autoSort: false
            , cols: Page.initColumn()
        });
        /**
         * 监听表格工具事件
         */
        // table.on('tool(' + Page.table-toolbar + ')', function (obj) {
        table.on('tool(actionTableRender)', function (obj) {
            //获得当前行数据
            var data = obj.data;
            //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var layEvent = obj.event;


            //查看操作
            if (layEvent === 'detail') {
                Page.openDetail(data);
            }
            //删除操作
            else if (layEvent === 'del') {
                Page.deleteAction(obj);
            }
            //删除操作
            else if (layEvent === 'load') {
                Page.loadAction(obj);
            }
            //编辑操作
            else if (layEvent === 'edit') {
                Page.openEdit(data);
            }
        });


        //监听行单击事件
        table.on('row(' + Page.tableId + ')', function (obj) {
            Page.clickAction(obj);
        });

        //监听行双击事件
        table.on('rowDouble(' + Page.tableId + ')', function (obj) {
            Page.doubleClickAction(obj);
        });

        function postTask(data) {
            var inputDataJson = JSON.stringify(data.field);
            var beginLocationJson = JSON.stringify(beginLocation);
            var endLocationJson = JSON.stringify(endLocations);
            $.ajax({
                url: CXL.ctxPath + '/semiautomatic/postTask',
                method: 'POST',
                datatype: 'JSON',
                data: {
                    craneId: currentSelectedCrane,
                    inputData: inputDataJson,
                    beginLocationList: beginLocationJson,
                    endLocationList: endLocationJson,
                },
                success: function (res) {
                    if (res.success) {
                        CXL.success("任务提交成功，即将开始！");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        }

        function postMixTask(data) {
            var inputDataJson = JSON.stringify(data.field);
            var area1Json = JSON.stringify(area1Location);
            var area2Json = JSON.stringify(area2Location);
            var area3Json = JSON.stringify(area3Location);
            var areaEndJson = JSON.stringify(areaEndLocation);
            $.ajax({
                url: CXL.ctxPath + '/semiautomatic/postMixTask',
                method: 'POST',
                datatype: 'JSON',
                data: {
                    craneId: currentSelectedCrane,
                    inputData: inputDataJson,
                    area1List: area1Json,
                    area2List: area2Json,
                    area3List: area3Json,
                    areaEndList: areaEndJson,
                },
                success: function (res) {
                    if (res.success) {
                        CXL.success("任务提交成功，即将开始！");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        }
        /**
         * 表格参数
         */
        var CombinationPage = {
            tableId: 'combinationTable',
            url: CXL.ctxPath + '/semiautomatic/combinationtask/combinationTable/datagrid',
            initColumn: function () {
                return [[
                    {type: 'numbers'}
                    , {field: 'id', title: 'ID', hide: true, width: 80}
                    , {field: 'name', title: '任务名称', width: 120}
                    , {fixed: 'right', title: '操作', toolbar: '#combination-table-toolbar', width: 170}
                ]];
            },
            deleteUrl: CXL.ctxPath + "/semiautomatic/combinationtask/combinationTable/delete",
            startUrl: CXL.ctxPath + "/semiautomatic/combinationtask/postTask"
        };


        /**
         * 页面查询
         */
        CombinationPage.searchAction = function () {
            var queryData = {};
            //查询字段
            queryData['workType'] = $("#tasktypeinput").val();
            queryData['craneId'] = $("#craneidinput").val();
            queryData['beginTime'] = $("#timeBegin").val();
            queryData['endTime'] = $("#timeEnd").val();

            // //排序字段
            // queryData['field'] = 'operatorTime';
            // queryData['order'] = 'desc';

            table.reload(CombinationPage.tableId, {where: queryData});
        }


        /**
         * 页面查询条件的重置
         */
        CombinationPage.resetAction = function () {
            let xdate = new Date("2019-04-30");
            // console.log(xdate);
            $("#tasktypeinput").val("");
            $("#craneidinput").val(0);
            $("#timeBegin").val(xdate);
            $("#timeEnd").val(new Date());
            CombinationPage.searchAction();
        }


        /**
         * 表格的单击事件
         */
        CombinationPage.clickAction = function (obj) {

        }

        /**
         * 表格的双击事件
         */
        CombinationPage.doubleClickAction = function (obj) {

        }


        /**
         * 查看
         */
        CombinationPage.openDetail = function (data) {
            var data = data.data;
            var layer = layui.layer;
            layer.open({
                type: 1,
                content: $('#openShowBox'),
                area: ['700px', '800px'], //宽高
                btn: ["确定"],
                success: function (index, layero) {

                    table.render({
                        elem: '#openShowTaskDetails'
                        , height: 'full-140'
                        , limit: 30
                        , autoSort: false
                        , url: CombinationPage.url + "/" + data.id
                        , Page: true
                        , cols: [[ //表头
                            {field: 'id', title: 'ID', width: 80}
                            , {field: 'name', title: '动作名称', width: 100}
                            , {field: 'craneId', title: '天车ID', width: 100}
                            , {field: 'workMode', title: '工作模式', width: 100}
                            , {field: 'catchNumber', title: '抓取次数', width: 100}
                            , {field: 'frequency', title: '运行次数', width: 180}
                        ]]
                    });

                }
            });
        }

        //删除动作组合任务
        CombinationPage.deleteAction = function (obj) {
            parent.layer.confirm('真的确定要删除么', function (index) {

                //提交 Ajax进行后端删除
                $.ajax({
                    type: "post",
                    url: CombinationPage.deleteUrl,
                    data: {id: obj.data.id},
                    success: function (res) {
                        if (res.success) {
                            CXL.success(res.msg);
                            //表格删除
                            obj.del();
                            combinationTable.reload();
                            // table.reload();
                        } else {
                            CXL.warn(res.msg);
                            // layer.msg(res.msg);
                        }
                    }
                });

                layer.close(index);
            });

        }
        //开始组合任务
        CombinationPage.startAction = function (obj) {
            let taskFrequency = $("#workFrequency").val();
            parent.layer.confirm('确认提交组合任务吗', function (index) {
                // console.log(obj.data);
                //提交 Ajax进行后端删除
                $.ajax({
                    type: "post",
                    url: CombinationPage.startUrl,
                    data: {craneid: currentSelectedCrane, combinationid: obj.id, taskFrequency: taskFrequency},
                    success: function (res) {
                        if (res.successf) {
                            CXL.success(res.msg);
                            combinationTable.reload();
                            // table.reload();
                        } else {
                            CXL.warn(res.msg);
                            // layer.msg(res.msg);
                        }
                    }
                });

                layer.close(index);
            });

        }
        /**
         * 表格渲染
         */
        var combinationTable = table.render({
            elem: '#' + CombinationPage.tableId
            , url: CombinationPage.url
            , page: true
            , limit: 10
            , autoSort: false
            , toolbar: CombinationPage.toolbar
            , where: CombinationPage.where
            , defaultToolbar: []

            , cols: CombinationPage.initColumn()
        });


        /**
         * 监听表格工具事件
         */
        table.on('tool(combinationTaskFilter)', function (obj) {
            //获得当前行数据
            var data = obj.data;
            //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var layEvent = obj.event;

            //查看操作
            if (layEvent === 'detail') {
                CombinationPage.openDetail(obj);
            }
            //删除操作
            else if (layEvent === 'delete') {
                CombinationPage.deleteAction(obj);
            }
            //编辑操作
            else if (layEvent === 'view') {
                CombinationPage.openEdit(data);
            } else if (layEvent === 'createWork') {
                CombinationPage.createWork(data);
            } else if (layEvent === 'start') {
                CombinationPage.startAction(data);
            }
        });

        displayTraState = function (e) {
            switch (e) {
                case "getTra1State":
                    displayStateIframe(1);
                    break;
                case "getTra2State":
                    displayStateIframe(2);
                    break;
                case "getTra3State":
                    displayStateIframe(3);
                    break;
                case "getTra4State":
                    displayStateIframe(4);
                    break;
            }
        }
        var stateIframeLoactin = ["lb", "['350', '50px']", ['100px', '100px'], "rb"]

        //弹出当前任务执行状态显示
        function displayStateIframe(id) {
            layer.open({
                title: id + "#天车",
                type: 2,
                zIndex: 0,
                area: ['400px', '350px'],
                shade: 0,
                offset: stateIframeLoactin[id - 1],
                content: CXL.ctxPath + '/semiautomatic/code/' + id
            });

        }

        //提交物料类型任务
        function postMaterialTask(data) {
            let inputDataJson = JSON.stringify(data.field);
            let endLocationJson = JSON.stringify(endLocations);
            $.ajax({
                url: CXL.ctxPath + '/semiautomatic/postMaterialTask',
                method: 'POST',
                datatype: 'JSON',
                data: {
                    inputData: inputDataJson,
                    endLocationList: endLocationJson,
                },
                success: function (res) {
                    if (res.success) {
                        CXL.success("任务提交成功，即将开始！");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });
        }


        function getCellMap() {
            $.ajax({
                url: '/boot/wms/cell/getCellMap',
                type: 'get',
                async: false,
                dataType: 'json',
                data:
                    {
                        x1: 7400,
                        x2: 255000,
                        y1: 3200,
                        y2: 29200,

                    },

                success: function (data) {
                    cellMap = data.cellMap;
                    // console.log(cellMap);
                    // cellLocations = data.cellMap;

                }
            });
        }

        function getZoneInfo() {
            $.ajax({
                url: '/boot/wms/zone/getZoneIdAndName',
                type: 'get',
                async: false,
                dataType: 'json',
                success: function (data) {
                    zoneInfoCollection = data.zoneandmaterial;
                    // console.log(cellMap);
                    // cellLocations = data.cellMap;

                }
            });
        }

        function getCellLocations() {
            $.ajax({
                url: '/boot/wms/cell/getCellMap',
                type: 'get',
                async: false,
                dataType: 'json',
                data:
                    {
                        x1: 7400,
                        x2: 255000,
                        y1: 3200,
                        y2: 29200,

                    },

                success: function (data) {
                    cellLocations = data.cellMap;
                }
            });
        }

        function getMaterial() {
            $.ajax({
                url: CXL.ctxPath + '/wms/materialtype/getdatalist',
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    materialList = data;
                    // console.log(materialList);
                    $.each(data, function (index, item) {
                        $('#materialTypeSelect').append(new Option(item.name, item.id));// 下拉菜单里添加元素
                    });
                    loadMaterialFlag = true;
                    // $('#materialTypeSelect').val($('#materialId')[0].value)
                    form.render('select', 'materialTask');
                }
            });
        }

        function getOutputMap() {
            $.ajax({
                url: '/boot/wms/output/getOutputMap',
                type: 'get',
                async: false,
                dataType: 'json',
                data: {
                    x1: 0,
                    x2: 250000,
                    y1: 0,
                    y2: 12000
                },
                success: function (data) {
                    outportMap = data.outputMap;
                }
            });
        }

        function initMap() {
            initImages();
            getPoolInfo();
            getCellMap();
            getOutputMap();
            getZoneInfo();
            initinfo();
            craneRuler.onload = function () {
                drawCellMap(xOffset, yOffset);
            };

            // getMaterial();
        }

        //初始化图片
        function initImages() {
            craneRuler.src = CXL.ctxPath + '/assets/semiautomatic/craneRuler11.png';
            craneimage1.src = CXL.ctxPath + '/assets/semiautomatic/crane1.png';
            craneimage2.src = CXL.ctxPath + '/assets/semiautomatic/crane2.png';
            craneimage3.src = CXL.ctxPath + '/assets/semiautomatic/crane3.png';
            craneimage4.src = CXL.ctxPath + '/assets/semiautomatic/crane4.png';
        }


//默认参数初始化
        function initinfo() {
            disabledLocations = [];
            for (let item of cellMap) {
                item.topleftx = (item.x / 100) * 1.5 + xOffset;
                item.toplefty = (item.y / 100) * 1.5 + yOffset;
                item.lowerrightx = (item.topleftx + 15);
                item.lowerrighty = (item.toplefty + 15);
                // item.color = colorArr[item.zoneId % 3];
                item.color = getCellColor(item);


                if (item.disabled === true) {
                    item.color = colorArr[4];
                    disabledLocations.push(item);
                }
            }
            //匹配上料仓名称
            for (let item of outportMap) {
                item["name"] = item.name;
                for (let item2 of corrections) {
                    if (item.name === item2.name) {
                        item["text"] = item2.text;

                        item["zoneId"] = 666;
                        if (item.disabled === true) {
                            item.color = colorArr[4];
                            disabledLocations.push(item);
                            break;
                        } else {
                            item.color = colorArr[2];
                            break;
                        }


                    }
                }
            }

        }

        //定时刷新高度
        function refreshCellMap() {
            getCellLocations();
            for (j = 0 , len = cellLocations.length; j < len; j++) {
                if (cellLocations[j].height != cellMap[j].height) {
                    cellMap[j].height = cellLocations[j].height;
                }
                if (cellMap[j].color != colorList.c5 && cellMap[j].color != colorList.cmax) {
                    cellMap[j].color = getCellColor(cellMap[j]);
                }

            }
            drawCellMap(xOffset, yOffset);
        }

//绘制整个池子
        function drawCellMap(xOffset, yOffset) {
            cellCanvasCtx.clearRect(0, 0, cellCanvas.width, cellCanvas.height);

            cellCanvasCtx.drawImage(craneRuler, 0, 20, 3800, 464);

            // console.log(cellMap);
            for (let item of cellMap) {
                drawRect(item.x / 100, item.y / 100, item.l / 100, item.w / 100, item.color);
                var heightn = new Number(item.height / 1000);
                drawText(cellCanvasCtx, item.x / 100 * 1.5, item.y / 100 * 1.5 + 10, ((String)(heightn.toFixed(1))), 'black', '10px "黑体"');
            }


            //绘制上料仓
            for (let item of outportMap) {
                // drawText(cellCanvasCtx, (item.x / 100) * 1.5, (item.y / 100) * 1.5 + 40, "■", item.color, '60px "黑体"');
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 25, (item.y / 100) * 1.5 + 26, "■", item.color, '60px "黑体"');
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 21, (item.y / 100) * 1.5 + 40 + 10, item.text, 'gray', '18px "楷体"');
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 26, (item.y / 100) * 1.5 + 40 + 27, "(" + item.materialName + ")", 'gray', '18px "楷体"');
                // ();
            }

            //绘制池子名称

            const set = new Set();
            for (let item of poolInfo) {
                if (set.has(item.name)) {
                    continue;
                }
                // drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 30, (item.y / 100) * 1.5 + 10, "■", item.color, '60px "黑体"');
                if (item.x != null) {
                    set.add(item.name)
                    drawText(cellCanvasCtx, item.x, item.y, item.name + "(" + item.materialName + ")", 'black', '18px "黑体"');
                }


                // console.log(item);
                // ();
            }


        }

//绘制一个矩形
        function drawRect(x, y, l, w, color) {
            // let ll = l / 2;
            // let ww = w / 2;
            // let xx = x - ll;
            // let yy = y - ww;
            cellCanvasCtx.fillStyle = color;
            cellCanvasCtx.fillRect(1.5 * x + xOffset, 1.5 * y + yOffset, 1.5 * (l - 1), 1.5 * (l - 1));

        }

        function drawText(ctx, x, y, text, color, font) {
            ctx.fillStyle = color;
            ctx.font = font;
            ctx.fillText(text, x + xOffset, y + yOffset);
        }

//池子点击监听
        function drawCellMap(xOffset, yOffset) {
            cellCanvasCtx.clearRect(0, 0, cellCanvas.width, cellCanvas.height);

            cellCanvasCtx.drawImage(craneRuler, 0, 20, 3800, 464);

            // console.log(cellMap);
            for (let item of cellMap) {
                drawRect(item.x / 100, item.y / 100, item.l / 100, item.w / 100, item.color);
                var heightn = new Number(item.height / 1000);
                drawText(cellCanvasCtx, item.x / 100 * 1.5, item.y / 100 * 1.5 + 10, ((String)(heightn.toFixed(1))), 'black', '10px "黑体"');
            }


            //绘制上料仓
            for (let item of outportMap) {
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 25, (item.y / 100) * 1.5 + 26, "■", item.color, '60px "黑体"');
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 21, (item.y / 100) * 1.5 + 40 + 10, item.text, 'gray', '18px "楷体"');
                drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 26, (item.y / 100) * 1.5 + 40 + 27, "(" + item.materialName + ")", 'gray', '18px "楷体"');
                // ();
            }
            //绘制池子名称

            const set = new Set();
            for (let item of poolInfo) {
                if (set.has(item.name)) {
                    continue;
                }
                // drawText(cellCanvasCtx, (item.x / 100) * 1.5 - 30, (item.y / 100) * 1.5 + 10, "■", item.color, '60px "黑体"');
                if (item.x != null) {
                    set.add(item.name)
                    drawText(cellCanvasCtx, item.x, item.y, item.name + "(" + item.materialName + ")", 'black', '18px "黑体"');
                }


                // console.log(item);
                // ();
            }
        }

//绘制一个矩形
        function drawRect(x, y, l, w, color) {
            // let ll = l / 2;
            // let ww = w / 2;
            // let xx = x - ll;
            // let yy = y - ww;
            cellCanvasCtx.fillStyle = color;
            cellCanvasCtx.fillRect(1.5 * x + xOffset, 1.5 * y + yOffset, 1.5 * (l - 1), 1.5 * (l - 1));

        }

        function drawText(ctx, x, y, text, color, font) {
            ctx.fillStyle = color;
            ctx.font = font;
            ctx.fillText(text, x + xOffset, y + yOffset);
        }

//池子点击监听
        //池子点击监听
        function areaClickCanvas(event) {
            let rect = cellCanvas.getBoundingClientRect();
            let x = event.clientX - rect.left * (cellCanvas.width / rect.width);
            let y = event.clientY - rect.top * (cellCanvas.height / rect.height);

            //检测选择屏蔽还是起终点
            if (isSelectDisabled === true) {
                for (let item of cellMap) {
                    if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                        if (item.color === colorArr[4]) {
                            cancelSetLocation(item, disabledLocations);
                        } else {
                            addLocation(item, disabledLocations, colorArr[4]);
                        }
                        drawCellMap(xOffset, yOffset);
                        break;
                    }
                }

                //如果选择的是上料仓
                for (let item of outportMap) {
                    let x1 = 1.5 * (item.x / 100);
                    let x2 = (1.5 * (item.x / 100)) + 60;
                    let y1 = 1.5 * (item.y / 100);
                    let y2 = (1.5 * (item.y / 100)) + 60;

                    if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
                        if (item.color === colorArr[4]) {
                            cancelSetLocation(item, disabledLocations);
                        } else {
                            addLocation(item, disabledLocations, colorArr[4]);
                        }
                        drawCellMap(xOffset, yOffset)
                        break;
                    }
                }


            }
            //混料模式的选择
            else if (isMixTaskMode) {
                for (let item of cellMap) {
                    if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                        if (item.color === colorArr[4]) {
                            CXL.error("当前区域已被屏蔽！")
                        } else if (item.color == colorList.c5) {
                            cancelSetLocation(item, area1Location);
                        } else if (item.color == colorList.c8) {
                            cancelSetLocation(item, area2Location);
                        } else if (item.color == colorList.c9) {
                            cancelSetLocation(item, area3Location);
                        } else if (item.color == colorList.cmax) {
                            cancelSetLocation(item, areaEndLocation);
                        } else {
                            if (selectMode == 1) {
                                addLocation(item, area1Location, colorList.c5);
                                // console.log(area1Location);
                            } else if (selectMode == 2) {
                                addLocation(item, area2Location, colorList.c8);
                                // console.log(area2Location);
                            } else if (selectMode == 3) {
                                addLocation(item, area3Location, colorList.c9);
                                // console.log(area3Location);
                            } else if (selectMode == 4) {
                                let flag = true;
                                if(areaEndLocation.length>0){
                                    for(let item of areaEndLocation){
                                        if(item.name.length < 5){
                                            flag = false;
                                            break;
                                        }
                                    }
                                }
                                if(flag) {
                                    addLocation(item, areaEndLocation, colorList.cmax);
                                }else{
                                    CXL.error("混料状态不能混合选点！")
                                }
                                // console.log(areaEndLocation);
                            }
                        }
                        drawCellMap(xOffset, yOffset);
                        break;
                    }

                }

                for (let item of outportMap) {
                    if (selectMode == 4) {
                        let x1 = 1.5 * (item.x / 100);
                        let x2 = (1.5 * (item.x / 100)) + 60;
                        let y1 = 1.5 * (item.y / 100);
                        let y2 = (1.5 * (item.y / 100)) + 60;

                        if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
                            if (item.color === colorList.cmax) {
                                cancelSetLocation(item, areaEndLocation);
                            } else {
                                if(areaEndLocation.length>0){
                                    CXL.error("混料只能单独选择上料仓或点")
                                }else {
                                    addLocation(item, areaEndLocation, colorList.cmax);
                                }
                            }
                            drawCellMap(xOffset, yOffset)
                            break;
                        }
                    }
                }


            } else {
                //检测是否选择区域
                if (isSelectRegion) {
                    for (let item of cellMap) {
                        if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                            if (beginZoneList.indexOf(item.zoneId) > -1) {
                                if (isSelectBegin) {

                                    for (let item1 of cellMap) {
                                        if (item.zoneId == item1.zoneId) {
                                            cancelSetLocation(item1, beginLocation);
                                        }
                                    }
                                    deleteFromArrayByElement(beginZoneList, item.zoneId);
                                    drawCellMap(xOffset, yOffset);

                                }
                            } else if (endZoneList.indexOf(item.zoneId) > -1) {
                                if (!isSelectBegin) {
                                    for (let item1 of cellMap) {
                                        if (item.zoneId == item1.zoneId) {
                                            cancelSetLocation(item1, endLocations);
                                        }
                                    }
                                    deleteFromArrayByElement(endZoneList, item.zoneId);
                                    drawCellMap(xOffset, yOffset);

                                } else {
                                    alert("当前区域已作为结束区域！")
                                }
                            } else {
                                // zoneList.push(item.zoneId);

                                if (isSelectBegin) {
                                    beginZoneList.push(item.zoneId);
                                } else {
                                    endZoneList.push(item.zoneId);
                                }
                                for (let item1 of cellMap) {
                                    if (item.zoneId == item1.zoneId) {
                                        if (isSelectBegin) {
                                            addLocation(item1, beginLocation, colorList.c5);

                                        } else {
                                            addLocation(item1, endLocations, colorList.cmax);
                                        }
                                    }
                                }
                                drawCellMap(xOffset, yOffset);
                                break;
                            }
                        }
                    }


                } else if (!isSelectRegion) {
                    for (let item of cellMap) {
                        if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                            if (item.color === colorArr[4]) {
                                CXL.error("当前区域已被屏蔽！")
                            } else if (item.color == colorList.c5) {
                                cancelSetLocation(item, beginLocation);
                            } else if (item.color == colorList.cmax) {
                                cancelSetLocation(item, endLocations);
                            } else {
                                if (isSelectBegin) {
                                    addLocation(item, beginLocation, colorList.c5);
                                } else if (!isSelectBegin) {
                                    addLocation(item, endLocations, colorList.cmax);
                                }
                            }
                            drawCellMap(xOffset, yOffset);
                            break;
                        }

                    }
                }
//如果选择的是上料仓
                for (let item of outportMap) {
                    let x1 = 1.5 * (item.x / 100) - 40
                    let x2 = 1.5 * (item.x / 100) + 40;
                    let y1 = 1.5 * (item.y / 100) - 40
                    let y2 = 1.5 * (item.y / 100) + 40;

                    if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
                        if (item.color === colorArr[4]) {
                            CXL.error("当前区域已被屏蔽！")
                        } else if (item.color == colorList.c5) {
                            cancelSetLocation(item, beginLocation);
                            deleteFromArrayByElement(beginZoneList, item.zoneId);

                        } else if (item.color == colorList.cmax) {
                            cancelSetLocation(item, endLocations);
                            deleteFromArrayByElement(endZoneList, item.zoneId);
                        } else {
                            if (isSelectBegin) {
                                if (checkIsMove()) {
                                    addLocation(item, beginLocation, colorList.c5);
                                } else {
                                    CXL.warn("上料仓不能作为抓点！");
                                }

                            } else if (!isSelectBegin) {
                                if (!checkIsPour()) {
                                    addLocation(item, endLocations, colorList.cmax);
                                } else {
                                    CXL.warn("倒料模式请勿选择上料仓作为放点！")
                                }
                            }
                        }
                        drawCellMap(xOffset, yOffset)
                        break;
                    }
                }
            }
        }


        //判断是否为倒料模式
        function checkIsPour() {
            if ($('input[name="selectWorkModel"]:checked').val() === "pour") {
                return true;
            } else {
                return false;
            }
        }

        //判断是否为移动模式
        function checkIsMove() {
            if ($('input[name="selectWorkModel"]:checked').val() === "move") {
                return true;
            } else {
                return false;
            }
        }


//选择点
        function addLocation(item, arr, color) {
            item.color = color;
            arr.push(item);
            refreshPointInput();
            //设置输入框同步
            $("#beginLocationInput").val(selectBeginInputTmp);
            $("#endLocationInput").val(selectEndInputTmp);
            $("#unwindLocationInput").val(selectEndInputTmp);
            // unwindLocationInput


        }

//取消选中
        function cancelSetLocation(item, arr) {
            if (item.zoneId == 666) {
                item.color = colorArr[2];
            } else {
                item.color = getCellColor(item);
            }
            deleteFromArrayByElement(arr, item);
            refreshPointInput();
            $("#beginLocationInput").val(selectBeginInputTmp);
            $("#endLocationInput").val(selectEndInputTmp);
            $("#unwindLocationInput").val(selectEndInputTmp);
        }

//输出数组指定元素
        function deleteFromArrayByElement(array, element) {
            array.forEach(function (item, index, arr) {
                if (item.name == element.name) {
                    arr.splice(index, 1);
                }
            });
        }

//分组元素
        function GroupBy(array, fn) {
            // debugger;
            const groups = {};
            array.forEach(function (item) {
                const group = JSON.stringify(fn(item));
                groups[group] = groups[group] || [];
                groups[group].push(item);
            });
            return Object.keys(groups).map(function (group) {
                return groups[group];
            });
        }

//刷新input框
        function refreshPointInput() {
            selectBeginInputTmp = [];
            selectEndInputTmp = [];
            for (var index in beginLocation) {
                selectBeginInputTmp.push(beginLocation[index].name);
            }
            for (var index in endLocations) {
                selectEndInputTmp.push(endLocations[index].name);
            }

        }

        //刷新Begininput框
        function refreshBeginPointInput() {
            selectBeginInputTmp = [];
            // selectEndInputTmp = [];
            for (var index in beginLocation) {
                selectBeginInputTmp.push(beginLocation[index].name);
            }

        }

        //刷新Endninput框
        function refreshEndPointInput() {
            // selectBeginInputTmp = [];
            selectEndInputTmp = [];
            for (var index in endLocations) {
                selectEndInputTmp.push(endLocations[index].name);
            }

        }

//颜色处理
//hex颜色转rgb颜色
        function HexToRgb(str) {
            var r = /^\#?[0-9A-F]{6}$/;
            //test方法检查在字符串中是否存在一个模式，如果存在则返回true，否则返回false
            //replace替换查找的到的字符串
            str = str.replace('#', '');
            //match得到查询数组
            var hxs = str.match(/../g);
            for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
            return hxs;
        }

//GRB颜色转Hex颜色
        function RgbToHex(a, b, c) {
            var r = /^\d{1,3}$/;
            // return window.alert('输入错误的rgb颜色值');
            var hexs = [a.toString(16), b.toString(16), c.toString(16)];
            for (var i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = '0' + hexs[i];
            return '#' + hexs.join('');
        }

//得到hex颜色值为color的加深颜色值，level为加深的程度，限0-1之间
        function getDarkColor(color, level) {
            var r = /^\#?[0-9A-F]{6}$/;
            var rgbc = HexToRgb(color);
            //floor 向下取整
            for (var i = 0; i < 3; i++) rgbc[i] = Math.floor(rgbc[i] * (1 - level));
            return RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
        }

//得到hex颜色值为color的减淡颜色值，level为加深的程度，限0-1之间
        function getLightColor(color, level) {
            var r = /^\#?[0-9A-F]{6}$/;
            var rgbc = HexToRgb(color);
            for (var i = 0; i < 3; i++)
                rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i]);
            return RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
        }

        function getCellColor(item) {

            let height = item.height;
            if (height < 1000) {
                return heightColorArr[0];
            } else if (height >= 1000 && height < 2000) {
                return heightColorArr[1];
            } else if (height >= 2000 && height < 3000) {
                return heightColorArr[2];
            } else if (height >= 3000 && height < 4000) {
                return heightColorArr[3];
            } else if (height >= 4000 && height < 5000) {
                return heightColorArr[4];
            } else if (height >= 5000 && height < 6000) {
                return heightColorArr[5];
            } else if (height >= 6000 && height < 7000) {
                return heightColorArr[6];
            } else if (height >= 7000 && height < 8000) {
                return heightColorArr[7];
            } else if (height >= 8000 && height < 9000) {
                return heightColorArr[8];
            } else if (height >= 9000) {
                return heightColorArr[9];
            }


        }

        function getOutputColor(item, color) {
            item.color = color;
        }


        // var websocket = null;
        //
        // function openWebSocket() {
        //     var url = "ws://" + window.location.hostname + ":8080/boot/semiautomatic/ws";
        //     //判断当前浏览器是否支持WebSocket
        //     if ('WebSocket' in window) {
        //         websocket = new WebSocket(url);
        //     } else {
        //         alert('当前浏览器 Not support websocket')
        //     }
        //     //连接发生错误的回调方法
        //     websocket.onerror = function () {
        //         console.log("WebSocket连接发生错误");
        //     };
        //     //连接成功建立的回调方法
        //     websocket.onopen = function () {
        //         console.log("WebSocket连接成功");
        //     }
        //     //接收到消息的回调方法
        //     websocket.onmessage = function (event) {
        //         // let mapData = JSON.parse(event.data);
        //         // var statusCollection = ["firstCraneStatus", "secondCraneStatus", "thirdCraneStatus", "fourthCraneStatus"];
        //         // var locationCollection = ["firstCraneLocation", "secondCraneLocation", "thirdCraneLocation", "fourthCraneLocation"];
        //         // for (const key in mapData) {
        //         //     if (statusCollection.indexOf(key) != -1) {
        //         //         if (mapData[key] === true) {
        //         //             drawColorLegend(key, heightColorArr[9]);
        //         //         } else {
        //         //             drawColorLegend(key, heightColorArr[0]);
        //         //         }
        //         //     } else if (locationCollection.indexOf(key) != -1) {
        //         //         if (key === "firstCraneLocation") {
        //         //             // console.log(mapData[key]);
        //         //             firstCraneLocation = mapData[key] * 1.5;
        //         //         } else if (key === "secondCraneLocation") {
        //         //             secondCraneLocation = mapData[key] * 1.5;
        //         //             // console.log(mapData[key]);
        //         //         } else if (key === "thirdCraneLocation") {
        //         //             thirdCraneLocation = mapData[key] * 1.5;
        //         //             // $("#bigCraneLocation").value(mapData[key] * 100);
        //         //
        //         //         } else if (key === "fourthCraneLocation") {
        //         //             fourthCraneLocation = mapData[key] * 1.5;
        //         //         }
        //         //         updateCraneLocations();
        //         //     }
        //         // }
        //     }
        //     //连接关闭的回调方法
        //     websocket.onclose = function () {
        //         console.log("WebSocket连接关闭");
        //     }
        // }
        //
        // function sendByWebsocketToGetCraneStatus() {
        //     var message = "getCraneStatue";
        //     websocket.send(message);
        // }
        //
        // function drawColorLegend(id, color) {
        //     // var object = document.getElementById(id);
        //     // object.style.color = color;
        //
        // }


        function stopCraneById(craneId) {
            CXL.confirm("确定停止该天车的任务吗？", function () {
                let loadIndex = CXL.load();
                $.ajax({
                    url: CXL.ctxPath + '/semiautomatic/stopWorkByTra',
                    method: 'GET',
                    datatype: 'JSON',
                    data: {tra: craneId},
                    success: function (res) {
                        CXL.closeByIndex(loadIndex, null);
                        if (res.success) {
                            CXL.success("任务停止成功。");
                        } else {
                            CXL.error(res.msg);
                        }
                    },
                    fail: function () {
                        CXL.closeByIndex(loadIndex, null);
                    }
                });
            });

        }

        stopTraByCraneClick = function (id) {
            // console.log(id.charAt(id.length - 1));
            stopCraneById((id.charAt(id.length - 1)));
        }
        //天车运行信息展示
        // var displayTraState = function(){
        //      console.log("Click Success！")
        //      // console.log(e.id);
        //  };
//任务暂停


        function windowToCanvas(x, y) {
            //返回元素的大小以及位置
            var bbox = cellCanvas.getBoundingClientRect();
            return {
                x: x - bbox.left * (cellCanvas.width / bbox.width),
                y: y - bbox.top * (cellCanvas.height / bbox.height)
            };

        }

//保存和恢复绘图面板

        function saveDrawingSurface() {
            drawingSurfaceImageData = cellCanvasCtx.getImageData(0, 0, cellCanvas.width, cellCanvas.height);
        }

        function restoreDrawingSurface() {
            cellCanvasCtx.putImageData(drawingSurfaceImageData, 0, 0);
        }

//Rubber bands


        function updateRubberbandRectangle(loc) {
            rubberbandRect.width = Math.abs(loc.x - mousedown.x);
            rubberbandRect.height = Math.abs(loc.y - mousedown.y);

            //从左往右拉，和从右往左拉的两种情况。主要是判断左边的位置
            //因为从左往右拉的时候，左边x坐标不变
            //从右往左拉的时候，左边线的x坐标需要跟着鼠标移动

            if (loc.x > mousedown.x) rubberbandRect.left = mousedown.x;
            else rubberbandRect.left = loc.x;

            if (loc.y > mousedown.y) rubberbandRect.top = mousedown.y;
            else rubberbandRect.top = loc.y;

            cellCanvasCtx.save();
            cellCanvasCtx.beginPath();
            cellCanvasCtx.rect(rubberbandRect.left, rubberbandRect.top, rubberbandRect.width, rubberbandRect.height);
            cellCanvasCtx.stroke();
            cellCanvasCtx.restore();
        }


        function drawRubberbandShape(loc) {
            cellCanvasCtx.beginPath();
            cellCanvasCtx.moveTo(mousedown.x, mousedown.y);
            cellCanvasCtx.lineTo(loc.x, loc.y);
            cellCanvasCtx.stroke();
        }


        function updateRubberband(loc) {
            //如果判断需要画矩形，就执行画矩形方法
            updateRubberbandRectangle(loc);
        }


        function drawHorizontalLine(y) {
            cellCanvasCtx.beginPath();
            cellCanvasCtx.moveTo(0, y + 0.5);
            cellCanvasCtx.lineTo(cellCanvas.width, y + 0.5);
            cellCanvasCtx.stroke();
        }


        function drawVerticalLine(x) {
            cellCanvasCtx.beginPath();
            cellCanvasCtx.moveTo(x + 0.5, 0);
            cellCanvasCtx.lineTo(x + 0.5, cellCanvasCtx.height);
            cellCanvasCtx.stroke();
        }

        function drawGuidewires(x, y) {
            cellCanvasCtx.save();
            cellCanvasCtx.strokeStyle = 'rgba(0,0,230,0.4)';
            cellCanvasCtx.lineWidth = 0.5;
            drawVerticalLine(x);
            drawHorizontalLine(y);
            cellCanvasCtx.restore();
        }


        function areaMouseDownCanvas(e) {
            // if (isSelectDisabled) {

            let rect = cellCanvas.getBoundingClientRect();
            let x = event.clientX - rect.left * (cellCanvas.width / rect.width);
            let y = event.clientY - rect.top * (cellCanvas.height / rect.height);
            //
            // x += 100;
            // y += 20;
            e.preventDefault();
            saveDrawingSurface();
            mousedown.x = x;
            mousedown.y = y;
            dragging = true;
            // }


        }


        function areaMouseMoveCanvas(e) {

            var loc;
            // console.log(loc);
            if (dragging) {
                e.preventDefault();
                loc = windowToCanvas(e.clientX, e.clientY);
                restoreDrawingSurface();
                updateRubberband(loc);
                // if (guidewires) {
                //     drawGuidewires(loc.x, loc.y);
                // }
            } else {
                // setTimeout("alert('对不起, 要你久候')", 3000 )
            }
            // drawCellMap();


        }


        function areaMouseUpCanvas(event) {
            let rect = cellCanvas.getBoundingClientRect();
            let x = event.clientX - rect.left * (cellCanvas.width / rect.width);
            let y = event.clientY - rect.top * (cellCanvas.height / rect.height);

            dragging = false;

            let beginx = 0;
            let endx = 0;
            let beginy = 0;
            let endy = 0;

            beginx = mousedown.x;
            beginy = mousedown.y;
            endx = x;
            endy = y;

            if (isSelectDisabled) {
                for (let item of cellMap) {
                    if (item.topleftx >= beginx - 2 && item.toplefty >= beginy - 2 && item.lowerrightx <= endx + 2 && item.lowerrighty <= endy + 2) {
                        if (item.color === colorArr[4]) {
                            cancelSetLocation(item, disabledLocations);
                        } else {
                            addLocation(item, disabledLocations, colorArr[4]);
                        }


                    }
                }
                drawCellMap(xOffset, yOffset);
                // console.log(disabledLocations);

            } else if (!isSelectDisabled && isMixTaskMode) {
                for (let item of cellMap) {
                    if (item.topleftx >= beginx - 2 && item.toplefty >= beginy - 2 && item.lowerrightx <= endx + 2 && item.lowerrighty <= endy + 2) {
                        if (item.color === colorList.cmax) {
                            cancelSetLocation(item, areaEndLocation);
                        } else if (item.color === colorList.c5) {
                            cancelSetLocation(item, area1Location);
                        } else if (item.color === colorList.c8) {
                            cancelSetLocation(item, area2Location);
                        } else if (item.color === colorList.c9) {
                            cancelSetLocation(item, area3Location);
                        } else if (item.color === colorArr[4]) {
                            // debugger;
                            layer.msg("当前区域内有屏蔽点！");
                        } else {
                            switch(selectMode){
                                case 1:
                                    addLocation(item, area1Location, colorList.c5);
                                    break;
                                case 2:
                                    addLocation(item, area2Location, colorList.c8);
                                    break;
                                case 3:
                                    addLocation(item, area3Location, colorList.c9);
                                    break;
                                case 4:
                                    addLocation(item, areaEndLocation, colorList.cmax);
                                    break;
                            }

                        }


                    }
                }
                drawCellMap(xOffset, yOffset);

            }
            else if (!isSelectDisabled && isSelectBegin) {
                for (let item of cellMap) {
                    // console.log(item.color);
                    if (item.topleftx >= beginx - 2 && item.toplefty >= beginy - 2 && item.lowerrightx <= endx + 2 && item.lowerrighty <= endy + 2) {
                        if (item.color === colorList.c5) {
                            cancelSetLocation(item, beginLocation);
                        } else if (item.color === colorList.cmax) {
                            cancelSetLocation(item, endLocations);
                        } else if (item.color === colorArr[4]) {
                            // debugger;
                            layer.msg("当前区域内有屏蔽点！");
                        } else {
                            addLocation(item, beginLocation, colorList.c5);
                        }


                    }
                }
                drawCellMap(xOffset, yOffset);

            } else if (!isSelectDisabled && !isSelectBegin) {
                for (let item of cellMap) {
                    if (item.topleftx >= beginx - 2 && item.toplefty >= beginy - 2 && item.lowerrightx <= endx + 2 && item.lowerrighty <= endy + 2) {
                        if (item.color === colorList.cmax) {
                            cancelSetLocation(item, endLocations);
                        } else if (item.color === colorList.c5) {
                            cancelSetLocation(item, beginLocation);
                        } else if (item.color === colorArr[4]) {
                            debugger;
                            layer.msg("当前区域内有屏蔽点！");
                        } else {
                            addLocation(item, endLocations, colorList.cmax);
                        }


                    }
                }
                drawCellMap(xOffset, yOffset);

            }
        }

        //池子点击监听
        function areaClickCanvas(event) {
            let rect = cellCanvas.getBoundingClientRect();
            let x = event.clientX - rect.left * (cellCanvas.width / rect.width);
            let y = event.clientY - rect.top * (cellCanvas.height / rect.height);

            //检测选择屏蔽还是起终点
            if (isSelectDisabled === true) {
                for (let item of cellMap) {
                    if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                        if (item.color === colorArr[4]) {
                            cancelSetLocation(item, disabledLocations);
                        } else {
                            addLocation(item, disabledLocations, colorArr[4]);
                        }
                        drawCellMap(xOffset, yOffset);
                        break;
                    }
                }

                //如果选择的是上料仓
                for (let item of outportMap) {
                    let x1 = 1.5 * (item.x / 100);
                    let x2 = (1.5 * (item.x / 100)) + 60;
                    let y1 = 1.5 * (item.y / 100);
                    let y2 = (1.5 * (item.y / 100)) + 60;

                    if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
                        if (item.color === colorArr[4]) {
                            cancelSetLocation(item, disabledLocations);
                        } else {
                            addLocation(item, disabledLocations, colorArr[4]);
                        }
                        drawCellMap(xOffset, yOffset)
                        break;
                    }
                }


            }
            //混料模式的选择
            else if (isMixTaskMode) {
                for (let item of cellMap) {
                    if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                        if (item.color === colorArr[4]) {
                            CXL.error("当前区域已被屏蔽！")
                        } else if (item.color == colorList.c5) {
                            cancelSetLocation(item, area1Location);
                        } else if (item.color == colorList.c8) {
                            cancelSetLocation(item, area2Location);
                        } else if (item.color == colorList.c9) {
                            cancelSetLocation(item, area3Location);
                        } else if (item.color == colorList.cmax) {
                            cancelSetLocation(item, areaEndLocation);
                        } else {
                            if (selectMode == 1) {
                                addLocation(item, area1Location, colorList.c5);
                                console.log(area1Location);
                            } else if (selectMode == 2) {
                                addLocation(item, area2Location, colorList.c8);
                                console.log(area2Location);
                            }else if (selectMode == 3) {
                                addLocation(item, area3Location, colorList.c9);
                                console.log(area3Location);
                            }else if (selectMode == 4) {
                                addLocation(item, areaEndLocation, colorList.cmax);
                                console.log(areaEndLocation);
                            }
                        }
                        drawCellMap(xOffset, yOffset);
                        break;
                    }

                }


            } else {
                //检测是否选择区域
                if (isSelectRegion) {
                    for (let item of cellMap) {
                        if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                            if (beginZoneList.indexOf(item.zoneId) > -1) {
                                if (isSelectBegin) {

                                    for (let item1 of cellMap) {
                                        if (item.zoneId == item1.zoneId) {
                                            cancelSetLocation(item1, beginLocation);
                                        }
                                    }
                                    deleteFromArrayByElement(beginZoneList, item.zoneId);
                                    drawCellMap(xOffset, yOffset);

                                }
                            } else if (endZoneList.indexOf(item.zoneId) > -1) {
                                if (!isSelectBegin) {
                                    for (let item1 of cellMap) {
                                        if (item.zoneId == item1.zoneId) {
                                            cancelSetLocation(item1, endLocations);
                                        }
                                    }
                                    deleteFromArrayByElement(endZoneList, item.zoneId);
                                    drawCellMap(xOffset, yOffset);

                                } else {
                                    alert("当前区域已作为结束区域！")
                                }
                            } else {
                                // zoneList.push(item.zoneId);

                                if (isSelectBegin) {
                                    beginZoneList.push(item.zoneId);
                                } else {
                                    endZoneList.push(item.zoneId);
                                }
                                for (let item1 of cellMap) {
                                    if (item.zoneId == item1.zoneId) {
                                        if (isSelectBegin) {
                                            addLocation(item1, beginLocation, colorList.c5);

                                        } else {
                                            addLocation(item1, endLocations, colorList.cmax);
                                        }
                                    }
                                }
                                drawCellMap(xOffset, yOffset);
                                break;
                            }
                        }
                    }


                } else if (!isSelectRegion) {
                    for (let item of cellMap) {
                        if (x >= item.topleftx && x < item.lowerrightx && y >= item.toplefty && y < item.lowerrighty) {

                            if (item.color === colorArr[4]) {
                                CXL.error("当前区域已被屏蔽！")
                            } else if (item.color == colorList.c5) {
                                cancelSetLocation(item, beginLocation);
                            } else if (item.color == colorList.cmax) {
                                cancelSetLocation(item, endLocations);
                            } else {
                                if (isSelectBegin) {
                                    addLocation(item, beginLocation, colorList.c5);
                                } else if (!isSelectBegin) {
                                    addLocation(item, endLocations, colorList.cmax);
                                }
                            }
                            drawCellMap(xOffset, yOffset);
                            break;
                        }

                    }
                }
//如果选择的是上料仓
                for (let item of outportMap) {
                    let x1 = 1.5 * (item.x / 100) - 40
                    let x2 = 1.5 * (item.x / 100) + 40;
                    let y1 = 1.5 * (item.y / 100) - 40
                    let y2 = 1.5 * (item.y / 100) + 40;

                    if (x - xOffset >= x1 && x - xOffset <= x2 && y + 10 >= y1 && y + 10 <= y2) {
                        if (item.color === colorArr[4]) {
                            CXL.error("当前区域已被屏蔽！")
                        } else if (item.color == colorList.c5) {
                            cancelSetLocation(item, beginLocation);
                            deleteFromArrayByElement(beginZoneList, item.zoneId);

                        } else if (item.color == colorList.cmax) {
                            cancelSetLocation(item, endLocations);
                            deleteFromArrayByElement(endZoneList, item.zoneId);
                        } else {
                            if (isSelectBegin) {
                                if (checkIsMove()) {
                                    addLocation(item, beginLocation, colorList.c5);
                                } else {
                                    CXL.warn("上料仓不能作为抓点！");
                                }

                            } else if (!isSelectBegin) {
                                if (!checkIsPour()) {
                                    addLocation(item, endLocations, colorList.cmax);
                                } else {
                                    CXL.warn("倒料模式请勿选择上料仓作为放点！")
                                }
                            }
                        }
                        drawCellMap(xOffset, yOffset)
                        break;
                    }
                }
            }
        }

//检查选定点域是否已被选定
        function Seleted(isSelectBegin, point) {
            if (isSelectBegin) {
                if (point.color == colorList.c5) {
                    return false;
                } else {
                    return true;
                }
            } else {
                if (point.color == colorList.cmax) {
                    return false;
                } else {
                    return true;
                }
            }
        }

//位置偏移量转换
        function addoffsety(value) {
            value += 40;
            return value;

        }

        function recoveroffsety(value) {
            value == 40;
            return value;

        }

        //重置起点
        resetBeginSelected = function () {
            for (let i = beginLocation.length - 1; i >= 0; i--) {
                cancelSetLocation(beginLocation[i], beginLocation);
            }

            drawCellMap(xOffset, yOffset);
            beginZoneList = [];

        }

        //重置终点
        resetEndSelected = function () {
            for (let i = endLocations.length - 1; i >= 0; i--) {
                cancelSetLocation(endLocations[i], endLocations);
            }
            drawCellMap(xOffset, yOffset);
            endZoneList = [];
        }
//重置选择
//重置选择
        resetSelected = function () {
            beginLocation = [];
            endLocations = [];
            beginZoneList = [];
            endZoneList = [];
            area1Location = [];
            area2Location = [];
            area3Location = [];
            areaEndLocation = [];
            refreshPointInput();
            $("#beginLocationInput").val(selectBeginInputTmp);
            $("#endLocationInput").val(selectEndInputTmp);
            $("#unwindLocationInput").val(selectEndInputTmp);
            initMap();


        }

        resetSelectedFree = function () {
            beginLocation = [];
            endLocations = [];
            beginZoneList = [];
            endZoneList = [];
            refreshPointInput();
            $("#beginLocationInput").val(selectBeginInputTmp);
            $("#endLocationInput").val(selectEndInputTmp);
            $("#unwindLocationInput").val(selectEndInputTmp);
            initMap();


        }
//清楚锁缓存
        deleteLocks = function () {
            $.ajax({
                url: CXL.ctxPath + "/semiautomatic/deleteLocks",
                data: {},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.success) {
                        CXL.success("清除成功。");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        }

        //清楚屏蔽
        deleteDisable = function () {
            $.ajax({
                url: CXL.ctxPath + "/semiautomatic/deleteDisableArea",
                type: "GET",
                dataType: "json",
                success: function (res) {
                    if (res.success) {
                        CXL.success("清除成功。");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        }


        function drawCraneLocation(x, y) {
            locationCanvas.width = locationCanvas.width;
            locationCanvasCtx.moveTo(0, y * 1.5 + yOffset + 7.5);
            locationCanvasCtx.lineTo(3800, y * 1.5 + yOffset + 7.5);
            locationCanvasCtx.lineWidth = 5;
            locationCanvasCtx.strokeStyle = "black";
            locationCanvasCtx.stroke();

            locationCanvasCtx.moveTo(x * 1.5 + xOffset + 7.5, 0);
            locationCanvasCtx.lineTo(x * 1.5 + xOffset + 7.5, 484);
            locationCanvasCtx.lineWidth = 5;
            locationCanvasCtx.strokeStyle = "black";
            locationCanvasCtx.stroke();
        }

        function updateCraneLocations() {
            craneCanvasCtx.clearRect(0, 0, craneCanvas.width, craneCanvas.height);


            // console.log(firstCraneLocation);
            // firstCraneLocation = firstCraneLocation * 1.5;
            // secondCraneLocation = secondCraneLocation * 1.5;
            // thirdCraneLocation = thirdCraneLocation * 1.5;
            // fourthCraneLocation = fourthCraneLocation * 1.5;


            craneCanvasCtx.drawImage(craneimage1, firstCraneLocation * 1.5 - 110, 0, 36, 36);
            craneCanvasCtx.drawImage(craneimage2, secondCraneLocation * 1.5 - 110, 0, 36, 36);
            craneCanvasCtx.drawImage(craneimage3, thirdCraneLocation * 1.5 - 110, 0, 36, 36);
            craneCanvasCtx.drawImage(craneimage4, fourthCraneLocation * 1.5 - 110, 0, 36, 36);

        }

        //获取渣池信息
        function getPoolInfo() {
            $.ajax({
                url: CXL.ctxPath + "/wms/pool/getPoolInfo",
                data: {},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.success) {
                        poolInfo = res.obj;
                        // flagStep --;
                        // console.log(poolInfo);
                        CXL.success("获取成功。");
                    } else {
                        CXL.error(res.msg);
                    }
                },
                fail: function () {
                    CXL.error("网络错误！");
                }
            });

        }
    }
);